package com.situ.mall.web.controller;


import com.situ.mall.common.entity.Comment;
import com.situ.mall.common.entity.Post;
import com.situ.mall.common.exception.MyException;
import com.situ.mall.common.mapper.CommentMapper;
import com.situ.mall.common.mapper.PostMapper;
import com.situ.mall.common.service.ICommentService;
import com.situ.mall.common.service.IPostService;
import com.situ.mall.common.vo.CommentVO;
import com.situ.mall.common.vo.PostVO;
import com.situ.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author JavaWizard
 * @since 2024-04-18
 */
@RestController
@RequestMapping("/client")
public class PostController {

    @Autowired
    private IPostService postService;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private CommentMapper commentMapper;

    // 获取帖子列表
    @GetMapping("/post/selectAll")
    public ResultVO selectAll() {
        return ResultVO.data(200, "请求成功", postMapper.selectAll());
    }

    // 发布帖子
    @PostMapping("/post/add")
    public ResultVO addPost(Post post) {
        System.out.println(post);
        if (post.getTitle() != null && post.getDetails() != null && post.getMemberId() != null) {
            // 获取当前时间
            post.setCreateTime(LocalDateTime.now());
            postMapper.insert(post);
        } else {
            throw new MyException("内容填写不完整");
        }
        return ResultVO.data(200, "请求成功", null);
    }

    // 获取帖子详情
    @GetMapping("/post/selectOne")
    public ResultVO selectOne(Integer id) {
        // 1.先去查帖子的内容
        PostVO postVO = postMapper.selectOne(id);

        // 2.查帖子的评论
        // 必须分开查，先查一级评论，再查二级评论，放到一级评论里，再查三级评论，放到二级评论里
        ArrayList<CommentVO> commentVOS = commentService.selectAll(id);

        // 3.再把帖子的评论放到帖子里面
        postVO.setCommentVOS(commentVOS);


        // 4.返回
        return ResultVO.data(200, "请求成功", postVO);
    }

    // 发布评论
    @PostMapping("/post/comment")
    public ResultVO comment(Comment comment) {
        if (comment.getPostId() != null && comment.getDetails() != null && comment.getMemberId() != null && comment.getReplay() != null) {
            // 获取当前时间
            comment.setCreateTime(LocalDateTime.now());
            commentMapper.insert(comment);
        } else {
            throw new MyException("内容填写不完整");
        }
        return ResultVO.data(200, "请求成功", null);
    }


}
